import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite';
import NutUIResolver from '@nutui/auto-import-resolver'
import vueSetupExtend from 'vite-plugin-vue-setup-extend';
import requireTransform from 'vite-plugin-require-transform';
import viteCompression from 'vite-plugin-compression';
import path from 'path'
import { VitePWA } from 'vite-plugin-pwa';
// import { visualizer } from 'rollup-plugin-visualizer';

const alias: Record<string, string> = {
  '@': path.resolve(__dirname, 'src'),
  'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
  '@components': path.resolve(__dirname, 'src/components'),
  '#': path.resolve(__dirname, './'),
};
// https://vitejs.dev/config/
export default defineConfig({
  // base: './',
  plugins: [
    vue({
      template: {
        compilerOptions: {
          // treat all tags with a dash as custom elements
          isCustomElement: (tag) => tag === "iconpark-icon",
        },
      },
    }),
    Components({
      resolvers: [NutUIResolver()],
    }),
    requireTransform({
      fileRegex: /.ts$|.vue$/,
    }),
    vueSetupExtend(),
    viteCompression({
      ext: '.gz',
      algorithm: 'gzip',  // 或 'brotli'
      threshold: 5120  // 小于 10KB 的文件不进行压缩
    }),
    VitePWA({
      registerType: 'autoUpdate', // 自动更新 Service Worker
      manifest: {
        name: 'PKBET',
        short_name: 'PKBET',
        theme_color: '#ffffff',
        icons: [
          {
            src: '/pwa/logo_192x192.png',
            sizes: '192x192',
            type: 'image/png',
          },
          {
            src: '/pwa/logo_512x512.png',
            sizes: '512x512',
            type: 'image/png',
          },
        ],
      },
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,jpg,jpeg,svg,webp,gif,json,woff2}'],
        runtimeCaching: [
          {
            urlPattern: /\.(?:js|css|html|json)$/, // JS, CSS, HTML 文件
            handler: 'CacheFirst', // 缓存优先
            options: {
              cacheName: 'static-assets',
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 30 * 24 * 60 * 60, // 30天
              },
            },
          },
          {
            urlPattern: /\.(?:png|jpg|jpeg|svg|gif|webp|ico)$/, // 图片
            handler: 'CacheFirst', // 缓存优先
            options: {
              cacheName: 'images',
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 60 * 24 * 60 * 60, // 60天
              },
            },
          }
        ],
        maximumFileSizeToCacheInBytes: 5 * 1024 * 1024
      },
    })
  ],
  css: {
    preprocessorOptions: {
      scss: {
        api: "modern",
      }
    }
  },
  resolve: { alias },
  server: {
    host: '0.0.0.0',
    port: 3000,

  },
  build: {
    outDir: 'dist', // 修改输出文件夹名称
    chunkSizeWarningLimit: 1000,
    rollupOptions: {  // 将资源分类到各自文件夹
      output: {
        chunkFileNames: 'resource/js/[name]-[hash].js',
        entryFileNames: 'resource/js/[name]-[hash].js',
        assetFileNames: 'resource/[ext]/[name]-[hash].[ext]',
        compact: true,
        manualChunks(id) {
          // 落地时需要的依赖 到一个独立的 chunk
          if (
            id.includes('node_modules/vue')
            || id.includes('node_modules/vue-router')
            || id.includes('node_modules/@vue')
            || id.includes('pinia')
            || id.includes('@nutui')
            || id.includes('@intlify')
            || id.includes('js-binary-schema-parser')
            || id.includes('@fingerprintjs')
            || id.includes('mitt')
            || id.includes('commonVar')
            || id.includes('Loading')
            || id.includes('Toast')
            || id.includes('protobufjs')
            || id.includes('base64')
            || id.includes('fastclick')
            || id.includes('svga')
            || id.includes('ieee')
            || id.includes('buffer')
            || id.includes('pako')
            || id.includes('dayjs')
            || id.includes('crypto-js')
          ) {
            return 'index-vendor';  // vue 和 vue-router 打包到 vue-vendor.js
          }

          // 网络协议
          if (id.includes('/NetPacket')) {
            return 'net-packet';
          }

          // 多语言 拆开
          if (id.includes('/zh-CN')) {
            return 'zh-CN';
          }
          if (id.includes('/en-US')) {
            return 'en-US';
          }
          if (id.includes('/vi-VN')) {
            return 'vi-VN';
          }

          // 按需拆分你的自定义模块或其他模块
          // 例如：node_modules
          if (id.includes('node_modules')) {
            const moduleName = id.split('node_modules/')[1].split('/')[0];
            return moduleName;
          }
        },
      },
      // plugins: [visualizer({
      //   open: true, // 自动打开浏览器
      //   filename: 'dist/stats.html', // 输出路径
      //   gzipSize: true, // 显示压缩后大小
      //   brotliSize: true, // 显示 Brotli 压缩后大小
      // }) as any],
    },
    target: 'esnext',
    minify: 'terser',
    // cssCodeSplit: true, // 启用 CSS 代码拆分
    sourcemap: false, // 构建后是否生成 source map 文件
    terserOptions: { //去除console和debugger
      compress: {
        // drop_console: true,
        drop_debugger: true
      }
    }
  }
})
